<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <!--TODO: 需要调整-->
            <el-form-item label="所在园区" prop="parkFoundationInfoId">
              <el-select v-model="queryParams.parkFoundationInfoId" placeholder="请选择所在园区">
                <el-option v-for="item in foundationInfoList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="楼&nbsp;&nbsp;栋&nbsp;&nbsp;号" prop="towerNumber">
              <el-input v-model="queryParams.towerNumber" placeholder="请输入楼栋号" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="房&nbsp;&nbsp;间&nbsp;&nbsp;号" prop="roomNumber">
              <el-input v-model="queryParams.roomNumber" placeholder="请输入房间号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="房间环境" prop="roomEnvironment">
              <el-select v-model="queryParams.roomEnvironment" placeholder="请选择房间环境" clearable>
                <el-option v-for="dict in parkr_building_room_environment" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="房间状态" prop="roomState">
              <el-select v-model="queryParams.roomState" placeholder="请选择房间状态" clearable>
                <el-option v-for="dict in parkbuilingroom_state" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="对&nbsp;&nbsp;接&nbsp;&nbsp;人" prop="contactPerson">
              <el-input v-model="queryParams.contactPerson" placeholder="请输入对接人" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <!--TODO: 需要调整-->
            <el-form-item label="承&nbsp;&nbsp;租&nbsp;&nbsp;人" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入承租人" clearable @keyup.enter="handleQuery"></el-input>
            </el-form-item>
            <!--TODO: 需要调整-->
            <el-form-item label="缴租频次" prop="frentPaymentFrequency">
              <el-input v-model="queryParams.frentPaymentFrequency" placeholder="请输入备注" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <!--TODO: 需要调整-->
            <el-form-item label="到期提醒" prop="expirationReminder">
              <el-select v-model="queryParams.expirationReminder" placeholder="请选择到期提醒">
                <el-option v-for="dict in park_expiration_reminder" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <div style="text-align: right">
          <el-button type="warning" icon="Download" @click="handleExport">导出 </el-button>
          <el-button plain icon="Plus" @click="handleOpen('create')"> 新增 </el-button>

          <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">删除 </el-button>
        </div>
      </template>

      <el-table v-loading="loading" :data="buildingList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="false" label="主键标识" align="center" prop="id" />
        <el-table-column v-if="false" label="园区基础信息主键" align="center" prop="parkFoundationInfoId" />
        <el-table-column label="序号">
          <template #default="scope">{{ scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column label="所在园区" align="center" prop="parkName" />
        <el-table-column label="楼栋号" align="center" prop="towerNumber" />
        <el-table-column label="房间号" align="center" prop="roomNumber" />
        <el-table-column label="建筑面积(㎡)" align="center" prop="floorArea" />
        <el-table-column label="房间环境" align="center" prop="roomEnvironment">
          <template #default="scope">
            <dict-tag :options="parkr_building_room_environment" :value="scope.row.roomEnvironment" />
          </template>
        </el-table-column>
        <el-table-column label="房间状态" align="center" prop="roomState">
          <template #default="scope">
            <dict-tag :options="parkbuilingroom_state" :value="scope.row.roomState" />
          </template>
        </el-table-column>
        <el-table-column label="对接人" align="center" prop="contactPerson" />
        <el-table-column label="承租人" align="center" prop="name" />
        <el-table-column label="租金(元/月)" align="center" prop="rents" />
        <el-table-column label="开始日期" align="center" prop="startTime" width="140">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束日期" align="center" prop="endTime" width="140">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="缴租频次" align="center" prop="frentPaymentFrequency">
          <template #default="scope">
            <dict-tag :options="park_frent_payment_frequency" :value="scope.row.frentPaymentFrequency" />
          </template>
        </el-table-column>
        <el-table-column label="到期提醒" align="center" prop="expirationReminder" />

        <el-table-column label="操作" fixed="right" align="center" width="120" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="编辑" placement="top">
              <el-button link type="primary" @click="handleOpen('update', scope.row.id, scope.row.parkRentId)"> 编辑 </el-button>
            </el-tooltip>
            <el-tooltip content="详情" placement="top">
              <el-button link type="primary" @click="handleOpen('detail', scope.row.id, scope.row.parkRentId)"> 详情 </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>

    <formDialog ref="formDialogRef" @success="handleSuccess" />
  </div>
</template>

<script setup name="Building" lang="ts">
import { listBuilding, getBuilding, delBuilding, addBuilding, updateBuilding } from '@/api/zichanguanli/parkbuilding/index';
import { BuildingVO, BuildingQuery, BuildingForm } from '@/api/zichanguanli/parkbuilding/types';
import { parkTenantForm } from '@/api/zichanguanli/parktenant/types';
import { getTenant, addTenant, updateTenant } from '@/api/zichanguanli/parktenant/index';
import { listFoundationInfoList } from '@/api/zichanguanli/foundationInfo';
import formDialog from './form.vue';
import { FoundationInfoVO, FoundationInfoQuery, FoundationInfoForm } from '@/api/zichanguanli/foundationInfo/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const parkBuildingDetailDialog = ref();

const {
  parkbuilingroom_state,
  park_expiration_reminder,
  parkr_building_room_environment,
  park_surrender_tenancy_status,
  park_frent_payment_frequency
} = toRefs<any>(
  proxy?.useDict(
    'parkbuilingroom_state',
    'park_expiration_reminder',
    'parkr_building_room_environment',
    'park_surrender_tenancy_status',
    'park_frent_payment_frequency'
  )
);

const buildingList = ref<BuildingVO[]>([]);
const buttonLoading = ref(false);
const foundationInfoList = ref<FoundationInfoVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const buildingFormRef = ref<ElFormInstance>();

const detailDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const formDialogRef = ref();
const handleOpen = (type: string, parkBuildingId?: string | number, parkRentId?: string | number) => {
  formDialogRef.value.open(type, parkBuildingId, parkRentId);
};
const handleSuccess = async (type: any) => {
  console.log('新增成功', type);
  if (type === 'create') {
    await proxy?.$modal.msgSuccess('新增成功');
    await resetQuery();
  } else if (type === 'update') {
    await proxy?.$modal.msgSuccess('修改成功');
    await resetQuery();
  }
};

/** 查询园区基础信息列表 */
const getParkList = async () => {
  loading.value = true;
  const res = await listFoundationInfoList();
  foundationInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: BuildingForm = {
  id: undefined,
  parkFoundationInfoId: undefined,
  towerNumber: undefined,
  floor: undefined,
  roomNumber: undefined,
  floorArea: undefined,
  roomEnvironment: undefined,
  roomState: undefined,
  contactPerson: undefined,
  remark: undefined,
  attachments: undefined
};
let parkerTenantForm = ref<parkTenantForm>();
const parkerTenantFormData: parkTenantForm = {
  id: undefined,
  parkBuildingId: undefined,
  name: undefined,
  frentPaymentFrequency: undefined,
  rents: undefined,
  contactInformation: undefined,
  startTime: undefined,
  endTime: undefined,
  remark: undefined,
  leaseTerm: undefined,
  propertyCostStandard: undefined,
  attachments: undefined,
  surrenderTenancyStatus: undefined,
  rentOutTime: undefined
};
parkerTenantForm.value = { ...parkerTenantFormData };
const data = reactive<PageData<BuildingForm, BuildingQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    parkFoundationInfoId: undefined,
    contactPerson: undefined,
    expirationReminder: undefined,
    frentPaymentFrequency: undefined,
    name: undefined,
    parkName: undefined,
    roomEnvironment: undefined,
    roomNumber: undefined,
    roomState: undefined,
    towerNumber: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '主键标识不能为空', trigger: 'blur' }],
    parkFoundationInfoId: [{ required: true, message: '园区基础信息主键;园区基础信息主键不能为空', trigger: 'blur' }],
    towerNumber: [{ required: true, message: '楼栋号不能为空', trigger: 'blur' }],
    floor: [{ required: true, message: '所在楼层不能为空', trigger: 'blur' }],
    roomNumber: [{ required: true, message: '房间号不能为空', trigger: 'blur' }],
    floorArea: [{ required: true, message: '建筑面积(㎡)不能为空', trigger: 'blur' }],
    roomEnvironment: [{ required: true, message: '房间环境不能为空', trigger: 'change' }],
    roomState: [{ required: true, message: '房间状态不能为空', trigger: 'change' }],
    contactPerson: [{ required: true, message: '对接人不能为空', trigger: 'change' }]
  }
});

const rules2 = {
  id: [{ required: true, message: '主键不能为空', trigger: 'blur' }],
  parkBuildingId: [{ required: true, message: '园区建筑信息主键不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '承租人不能为空', trigger: 'blur' }],
  frentPaymentFrequency: [{ required: true, message: '缴租频次不能为空', trigger: 'change' }],
  rents: [{ required: true, message: '租金不能为空', trigger: 'blur' }],
  startTime: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
  endTime: [{ required: true, message: '结束时间不能为空', trigger: 'blur' }]
};
const { queryParams, form, rules } = toRefs(data);

/** 查询园区建筑信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listBuilding(queryParams.value);
  buildingList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  parkerTenantForm.value = { ...parkerTenantFormData };
  buildingFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  // queryParams.value = {
  //   pageNum: 1,
  //   pageSize: 10,
  //   parkFoundationInfoId: undefined,
  //   contactPerson: undefined,
  //   expirationReminder: undefined,
  //   frentPaymentFrequency: undefined,
  //   name: undefined,
  //   parkName: undefined,
  //   roomEnvironment: undefined,
  //   roomNumber: undefined,
  //   roomState: undefined,
  //   towerNumber: undefined,
  //   contactPerson: undefined,
  //   frentPaymentFrequency: undefined,
  //   params: {}
  // }
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: BuildingVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加园区建筑信息';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: BuildingVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getBuilding(_id);
  const parkerTenantRes = await getTenant(_id);
  Object.assign(form.value, res.data);
  Object.assign(parkerTenantForm.value, parkerTenantRes.data);
  dialog.visible = true;
  dialog.title = '修改园区建筑信息';
};

const handleDetail = async (row?: BuildingVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getBuilding(_id);
  const parkerTenantRes = await getTenant(_id);
  Object.assign(form.value, res.data);
  Object.assign(parkerTenantForm.value, parkerTenantRes.data);
  detailDialog.visible = true;
  detailDialog.title = '园区建筑信息详情';
};

/** 提交按钮 */
const submitForm = () => {
  buildingFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateBuilding(form.value);
        await updateTenant(parkerTenantForm.value).finally(() => (buttonLoading.value = false));
      } else {
        const res = await addBuilding(form.value);
        console.log(res);
        parkerTenantForm.value.parkBuildingId = res.data;
        await addTenant(parkerTenantForm.value);
        buttonLoading.value = false;
      }
      buttonLoading.value = false;
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: BuildingVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('确定删除所选的信息吗？').finally(() => (loading.value = false));
  await delBuilding(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'zichanguanli/building/export',
    {
      ...queryParams.value
    },
    `building_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
  getParkList();
});
</script>
<style scoped>
::v-deep .el-form--inline .el-input,
.el-form--inline .el-select {
  width: 200px;
}

/* el-table 列数据为空自动显示 -- */
::v-deep .el-table .el-table__body td .cell:empty::after,
.el-table .el-table__body td .cell > span:empty::after,
.el-table .el-table__body td .cell .approval:empty::after,
.el-table .el-table__body td .cell div:empty::after,
.el-table .el-table__body td .cell .line-limit-length:empty::after {
  content: '-';
}
</style>
